const express = require("express");
const router = express.Router();
const { verify } = require("../utils/jwt");
const cartModel = require("../db/model/shopCarModel");
const userModel = require("../db/model/userModel");

router.post("/add", async (req, res) => {
  const { name, price, num, token } = req.body;

  if (!token) ({ msg: "token缺失", code: -999 });
  // 根据token解析出用户信息
  let info = {};
  try {
    info = await verify(token);
  } catch (error) {
    return res.send({ msg: "token非法", code: -998, error });
  }
  // token 是否已经被替换  根据token 和 id 查询数据库是否存在对应的数据 如果存在那就是没有问题
  const tokenIsHava = await userModel.findOne({ _id: info._id, token });
  if (!tokenIsHava) return res.send({ msg: "token失效", code: -997 });
  const result = await cartModel.insertMany({
    name,
    price,
    num,
    uid: info._id,
  });
  if (!result) return res.send({ msg: "加入购物车失败", code: -1 });
  res.send({ msg: "加入购物车成功", code: 0 });
});

module.exports = router;
